package com.example.recyclerview5;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Bundle;
import android.widget.Toast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用SwipeRefreshLayout实现下拉刷新
 */

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;

    private ProductListAdapter productListAdapter;

    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取RecyclerView
        recyclerView  = findViewById(R.id.recyclerView);

        // 设置RecyclerView的productListAdapter
        ArrayList<Product> products = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            products.add(new Product(Long.valueOf(i), "商品" + i, "风格" + i, i, new BigDecimal(i + ".99")));
        }
        products.add(new Product(20L, "klasjehglkejhfglkesdruhglkehstjgkegsrhjgkrshtgeosjr商品", "风格20", 20, new BigDecimal("20.99")));
        productListAdapter = new ProductListAdapter(products);
        recyclerView.setAdapter(productListAdapter);


        // 处理下拉刷新
        swipeRefreshLayout = findViewById(R.id.refreshLayout);
        // 设置刷新时转圈圈的颜色
        swipeRefreshLayout.setColorSchemeResources(R.color.purple_700);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 一般来说要开一个线程去搞数据
                Toast.makeText(MainActivity.this, "下拉刷新", Toast.LENGTH_SHORT).show();
                // 添加一条数据
                products.add(0, new Product(-1L, "新的数据", "风格刚刚", 234, new BigDecimal("546.6")));
                // 更新ui
                productListAdapter.notifyDataSetChanged();
                // 停止刷新（不然上面会有个东西一直转个不停，转着就不能再触发这个刷新接口了）
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }
}